<?php
declare (strict_types = 1);

namespace app\controller\admin;

use think\Request;
use app\traits\MyControllerTrait;
use app\model\AdminRole;
use app\model\AdminUser;
use think\facade\Session;
use app\validate\admin\AdminBindRoleValidate;
use think\exception\ValidateException;
use app\event\AdminActionEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;

class AdminBindRoleController
{
  use MyControllerTrait;

  protected string $uri = '/admin/bind-role';

  public function create(Request $request)
  {
      $admin_user_id = $request->get('admin_user_id/d', 0);

      // 表单校验
      if (is_numeric($admin_user_id) === false || 1 > $admin_user_id) return json(['code' => 0, 'message' => "未知管理员账户"]);

      $adminUser  = AdminUser::whereRaw('id = :id', ['id' => $admin_user_id])->findOrEmpty();
      if ($adminUser->isEmpty()) return json(['code' => 0, 'message' => '管理员 ID 不存在']);

      $data = [
          'uri'             => $this->uri,
          'admin_user_id'   => $admin_user_id,
          'admin_role_id'   => $adminUser->admin_role_id,
          'roles'           => AdminRole::field('id, title')->select()->toArray(),
          'account'         => $adminUser->account,
          '__token__'       => $request->buildToken(),
      ];
      return view($this->uri.'/'.__FUNCTION__, $data);
  }// create() end

    public function store(Request $request)
    {
        $admin_user_id = $request->post('admin_user_id/d', 0);// admin_user.id
        $admin_role_id = $request->post('admin_role_id/d', 0);// admin_role.id

        // 表单校验
        $check_data = [
            'admin_user_id' => $admin_user_id,
            'admin_role_id' => $admin_role_id,
        ];
        try {
            validate(AdminBindRoleValidate::class)->check($check_data);
        } catch (ValidateException $validateException) {
            return json(['code' => 0, 'message' => $validateException->getError()]);
        }

        $adminUser = AdminUser::whereRaw('id = :id', ['id' => $admin_user_id])->findOrEmpty();
        if ($adminUser->isEmpty()) return json(['code' => 0, 'message' => '管理员 ID 不存在']);

        $adminRole = AdminRole::whereRaw('id = :id', ['id' => $admin_role_id])->findOrEmpty();
        if ($adminRole->isEmpty()) return json(['code' => 0, 'message' => '角色 ID 不存在']);
        if ($request->checkToken('__token__') === false) return json(['code' => 0, 'message' => '页面失效,请刷新页面']);

        $adminUser->admin_role_id    = $admin_role_id;
        $adminUser->save();
        Session::set('admin_user.admin_role_id', $admin_role_id);

        $check_data = [
            'admin_user_id' => AdminUser::where('id', $admin_user_id)->value('account') ?? $admin_user_id,
            'admin_role_id' => AdminRole::where('id', $admin_role_id)->value('title') ?? $admin_role_id,
        ];
        $data = [
            $this->getPermissionTitle($this->uri.'/'.__FUNCTION__),
            Session::get('admin_user.account'),
            $check_data
        ];
        (new EventDispatcher)->dispatch((new AdminActionEvent($request, $data)), AdminActionEvent::EVENT_NAME);
        return json(['code' => 1, 'message' => '保存成功']);
    }// store() end
}
